import Compressor from 'compressorjs';
import {mapState,mapMutations} from 'vuex'
const uploadMixin = {
    computed:{
        ...mapState(['uploadImgList','serverUrl2','CompanyCode','appid','UploadLock','SwitchPhoto'])
    },
    methods:{
        ...mapMutations([
            'UPLOADIMGLIST','CONCLUSION','UPLOAD_LOCK'
        ]),
        postSts(url,data){
            let that = this
            let OSS = require('ali-oss')
            return new Promise((resolve,reject)=>{
                that.$api.upload.getSts({ossBuckFlag:'privateFet'}).then(res=>{
                    let client = new OSS({
                        endpoint:'oss-cn-shenzhen.aliyuncs.com',
                        accessKeyId:res.accessKeyId,
                        accessKeySecret:res.accessKeySecret,
                        stsToken: res.securityToken,
                        bucket:process.env.VUE_APP_OSSBUCKET
                    })
                    console.log('上传权限最高oss')
                    client.multipartUpload(url,data).then(res=>{
                        resolve(url)
                    }).catch(res=>{
                        reject('')
                    })
                }) 
            })   
        },
        compressor(localData,url){
            let _this = this
            return new Promise((resolve,reject)=>{
                if(localData.size>(2*1024*1024)){
                    new Compressor(localData, {
                        quality: 0.7,
                        success(result) {
                            _this.postSts(url,result).then(res=>{
                                resolve({url:res,size:localData.size/(1024*1024)})
                            }).catch(()=>{
                                reject('')
                            })
                        },
                        error(err) {
                          console.log(err.message);
                          reject('')
                        },
                      });
                  } else {
                    _this.postSts(url,localData).then(res=>{
                        resolve({url:res,size:localData.size/(1024*1024)})
                    }).catch(()=>{
                        reject('')
                    })
                  }
            })
        },
        wxUploadImage:function(localIds){
            let _this = this
            let newDate = new Date();
            let fileName, newBus, monthnum, folderName, url;
            let fileType = 'jpg'
            if(!sessionStorage.getItem('BUSINESSNO')){
                let numonee = _this.randomString(12)
                newBus = ("000000000000000000000000000000" + numonee + newDate.getTime()).substr(-30)
                // _this.BUSINESSNO(newBus)
                sessionStorage.setItem('BUSINESSNO',newBus)
            } else {
                newBus = sessionStorage.getItem('BUSINESSNO')
            }
            if ((newDate.getMonth() + 1) > 9) {
                monthnum = newDate.getMonth() + 1
            } else {
                monthnum = "0" + "" + (newDate.getMonth() + 1)
            }
            fileName = `${newBus}-${_this.uploadImgList.length+1}.${fileType}`;
            folderName = newDate.getFullYear() + "" + monthnum + "" + newDate.getDate()
            url = `ast_image/ASSIST/UploadImage/${folderName}/${localStorage.getItem('userId')}/${fileName}`
            _this.UPLOAD_LOCK(false)
            return new Promise((resolve,reject)=>{
                _this.compressor(localIds,url).then(res=>{
                        let params = {
                                bussinessNo: sessionStorage.getItem('BUSINESSNO'),
                                imageName: fileName,
                                companyCode: _this.CompanyCode,
                                ossPathUrl:res.url,
                                size:res.size,
                                appid: _this.appid,
                                index:_this.uploadImgList.length>0?1:0,
                                isValid:'Y'
                        }
                        let tiemr = setTimeout(()=>{
							if(!_this.UploadLock){
                                _this.UPLOAD_LOCK(true)
                                let obj = {
                                    imgName:fileName,
                                    localId:params.ossPathUrl,
                                    isValid:'Y',
                                    imgUrl:window.URL.createObjectURL(localIds)
                                }
                                _this.UPLOADIMGLIST([..._this.uploadImgList,obj])
                                reject({
                                    companyCode:_this.CompanyCode,
                                    imgName:fileName
                                })
							}
						},10000)
                        _this.$api.upload.imageNature(params).then(res1=>{
                            clearTimeout(tiemr)
                            _this.UPLOAD_LOCK(true)
                            let obj = {
                                imgName:fileName,
								localId: params.ossPathUrl,
                                isValid:'Y',
                                imgUrl:window.URL.createObjectURL(localIds)
                            }
                            _this.UPLOADIMGLIST([..._this.uploadImgList,obj])
                            res1.imgName = fileName
                            resolve(res1)
                        }).catch(res1=>{
                            clearTimeout(tiemr)
                            _this.UPLOAD_LOCK(true)
                            let obj = {
                                imgName:fileName,
								localId:params.ossPathUrl,
                                isValid:'Y',
                                imgUrl:window.URL.createObjectURL(localIds)
                            }
                            _this.UPLOADIMGLIST([..._this.uploadImgList,obj])
                            reject({
                                companyCode:_this.CompanyCode,
                                imgName:fileName
                            })
                        }) 
                }).catch(res=>{
                    reject('')
                })
            })
        },
        wxChooseImage:function(){
            let _this = this
            return new Promise((resolve,reject)=>{
                wx.chooseImage({
                    count: 1,
                    sizeType: ['original'],
                    sourceType: _this.SwitchPhoto == 0 ? ['camera'] : ['album', 'camera'],
                    success(res){
                        resolve({localIds:res.localIds})
                    },
                    fail(res){
                        reject(res)
                    }
                })
            })
            
        },
        randomString(len) {
            len = len || 32;
            let timestamp = new Date().getTime();
            /****默认去掉了容易混淆的字符oOLl,9gq,Vv,Uu,I1****/
            let $chars = 'ABCDEFGHJKMNPQRSTWXYZabcdefhijkmnprstwxyz2345678';
            let maxPos = $chars.length;
            let randomStr = '';
            for (let i = 0; i < len; i++) {
                randomStr += $chars.charAt(Math.floor(Math.random() * maxPos));
            }
            return randomStr;
        },
    }
}
export default uploadMixin